package org.example.message_queue.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.message_queue.common.ConsumerEnv;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/*
*存储消息的队列
*/
public class MSGQueue {
    private String name;
    private boolean durable = false;
//    独占功能
    private boolean exclusive = false;

    private boolean autoDelete = false;

    private Map<String, Object> arguments = new HashMap<>();

    private List<ConsumerEnv> consumerEvnList = new LinkedList<>();
//    记录当前取到第几个消费者，方便实现轮询策略
    private AtomicInteger consumerSeq = new AtomicInteger();
//    增加新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv){
        synchronized (this){
            consumerEvnList.add(consumerEnv);
        }
    }

//    删除订阅者
//    挑选一个订阅者，来处理当前消息（轮训的方式）
    public ConsumerEnv chooseConsumer(){
//        是0的时候就意味着没有消费者订阅该队列
        if (consumerEvnList.size()==0){
            return null;
        }
//        计算当前要取的元素下标
        int index = consumerSeq.get() % consumerEvnList.size();
//        自增
        consumerSeq.getAndIncrement();
        return consumerEvnList.get(index);
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }


    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }
    
    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

//    测试用例使用
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object value){
        arguments.put(key,value);
    }
    public void setArguments(Map<String, Object> arguments){
        this.arguments = arguments;
    }
}
